﻿using AikeShoop.Common;
using AikeShoopPro.Admin.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;

namespace AikeShoopPro.Admin.Controllers
{
    public class AccountController : BaseController
    {
        private readonly static ValidateCodeHelper validateCode = new ValidateCodeHelper();
        public IActionResult Index()
        {
            return View();
        }

        //登陆操作
        public IActionResult Login(string ReturnUrl)
        {
            ViewData["ReturnUrl"] = ReturnUrl;
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Login(UserLoginInfo userLogin)
        {
            if (userLogin.username != "123" && userLogin.password != "123")
                return RedirectToAction(nameof(Login));

            //进行授权认证
            var claims = new List<Claim>()  //存放 用户相关信息
            {
                new Claim(ClaimTypes.Name,userLogin.username),
            };

            //设置管道
            var claimsIdentity = new ClaimsIdentity(claims,
                CookieAuthenticationDefaults.AuthenticationScheme);

            // 自动发送 token 给客户端，并生成 cookies
            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                new ClaimsPrincipal(claimsIdentity),
                new AuthenticationProperties
                {
                    IsPersistent = true,
                    ExpiresUtc = DateTime.UtcNow.AddMinutes(2),
                    AllowRefresh = true
                });

            //认证成功 返回 ReturnUrl 上
            return Redirect(userLogin.ReturnUrl ?? "/");
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Logout()
        {
            await HttpContext.SignOutAsync();
            return RedirectToAction(nameof(Login));
        }


        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <returns></returns>
        public ActionResult GetValidateCode()
        {

            //创建验证码
            string code = validateCode.CreateValidateCode(4);

            //创建图片验证码
            byte[] bytes = validateCode.CreateValidateGraphic(code);

            return File(bytes, @"image/jpeg");
        }

        
    }
}
